package com.gxitsky.plugin;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import sun.misc.Launcher;
import sun.misc.URLClassPath;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

@SpringBootApplication
public class ServerProviderApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(ServerProviderApplication.class, args);
//        loadJar();
    }

    public static void loadJar() throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
//        URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
//        ClassLoader classLoader1 = ServerProviderApplication.class.getClassLoader();
//        ClassLoader classLoader2 = IFunction.class.getClassLoader();

//        ClassLoader urlClassLoader = ClassLoader.getSystemClassLoader();
//        URLClassLoader urlClassLoader = (URLClassLoader) ServerProviderApplication.class.getClassLoader();

        URL url = new URL("jar:file:///D:/service-impl-1.0.0-SNAPSHOT.jar!/");
        URLClassLoader classLoader = new URLClassLoader(new URL[]{url});
        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
        JarFile jarFile = jarURLConnection.getJarFile();
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            String entryName = jarEntry.getName();
            String className = entryName.replace("/", ".");
            if (jarEntry.isDirectory() || !className.startsWith("com.gxitsky.plugin") || !className.endsWith(".class")) {
                continue;
            }
            String classPath = className.substring(0, entryName.length() - 6);
            Class<?> clazz = classLoader.loadClass(classPath);
            boolean assignableFrom = IFunction.class.isAssignableFrom(clazz);
            System.out.println(assignableFrom);
            IFunction function = (IFunction) clazz.newInstance();
            String name = function.getName();
            System.out.println(name);




//            boolean localClass = clazz.isLocalClass();
//            System.out.println("localClass:" + localClass);
//            boolean anInterface = clazz.isInterface();
//            boolean assignableFrom3 = IFunction.class.isAssignableFrom(clazz);
//            System.out.println(className + ":" + assignableFrom3);
        }
    }

}
